const SERVER_BASE_PATH = "http://localhost:8088";

/**
 * 将结果显示至页面
 * @param {} result
 */
function resultToResult(result) {
    if (result["success"]) {
        $(".codeResult").html(result["message"]);
    }
    if (result['message'] instanceof Array) {
        var data = result['message'];
        var html = "";

        var length = data.length;

        for (var i = 0; i < length; i++) {
            html += `
                ${data[i]} <br>
            `;
        }

        $(".codeResult").html(html);

        return;
    }
}

var codeEditor = CodeMirror.fromTextArea(document.getElementById("code"), {
    lineNumbers: true,//行显示
    matchBrackets: true,
    mode: "text/x-c++src",//对应的mine值
    indentUnit: 4,//缩进单位
    // theme:"monokai",//主题
    scrollbarStyle: "simple",//滚动条样式
    smartIndent: true,//自动缩进
    styleActiveLine: true,//光标行高亮
    //全屏模式
    fullScreen: true,
    //快捷键
    extraKeys: {
        "Alt-Space": "autocomplete",//ctrl-space唤起智能提示
        "F11": function (cm) {
            cm.setOption("fullScreen", !cm.getOption("fullScreen"));
        },
        "Esc": function (cm) {
            if (cm.getOption("fullScreen")) cm.setOption("fullScreen", false);
        },
        "Ctrl-/": "toggleComment",
        "Ctrl-S": function () {
            $('#save').click();
        },
        "Ctrl-Z": function (editor) {
            codeEditor.undo();
        },//undo
        "F8": function (editor) {
            codeEditor.redo();
        },//Redo
        "F7": function autoFormat(cm) {
            var totalLines = cm.lineCount();
            cm.autoFormatRange({line: 0, ch: 0}, {line: totalLines});
        }//代码格式化
    }
});

//阻止浏览器默认行为
function stopDefault(e) {
    //防止浏览器默认行为(W3C)
    if (e && e.preventDefault) {
        e.preventDefault();
    }
    //IE中组织浏览器行为
    else {
        window.event.returnValue = false;
        return false;
    }
}

//刷新编辑器
var editorRefresh = function () {
    setTimeout(function () {
        codeEditor.refresh(); //:刷新编辑器
    }, 1000);
};

CodeMirror.commands.autocomplete = function (cm) {//自动补齐
    stopDefault();
    // cm.showHint({hint: CodeMirror.hint.anyword});
    cm.showHint();
};

CodeMirror.defineExtension("autoFormatRange", function (from, to) {//格式化
    var cm = this;
    var outer = cm.getMode(), text = cm.getRange(from, to).split("\n");
    var state = CodeMirror.copyState(outer, cm.getTokenAt(from).state);
    var tabSize = cm.getOption("tabSize");

    var out = "", lines = 0, atSol = from.ch == 0;

    function newline() {
        out += "\n";
        atSol = true;
        ++lines;
    }

    for (var i = 0; i < text.length; ++i) {
        var stream = new CodeMirror.StringStream(text[i], tabSize);
        while (!stream.eol()) {
            var inner = CodeMirror.innerMode(outer, state);
            var style = outer.token(stream, state), cur = stream.current();
            stream.start = stream.pos;
            if (!atSol || /\S/.test(cur)) {
                out += cur;
                atSol = false;
            }
            if (!atSol && inner.mode.newlineAfterToken &&
                inner.mode.newlineAfterToken(style, cur, stream.string.slice(stream.pos) || text[i + 1] || "", inner.state))
                newline();
        }
        if (!stream.pos && outer.blankLine) outer.blankLine(state);
        if (!atSol) newline();
    }

    cm.operation(function () {
        cm.replaceRange(out, from, to);
        for (var cur = from.line + 1, end = from.line + lines; cur <= end; ++cur)
            cm.indentLine(cur, "smart");
        cm.setSelection(from, cm.getCursor(false));
    });
});

codeEditor.on("change", function (cm) {
    // console.log('111');
    // cm.showHint({hint: CodeMirror.hint.anyword});
});

codeEditor.on("keypress", () => {
    //编译器内容更改事件
    // console.log(codeEditor.CodeMirrorEditor);
    codeEditor.showHint();
});

//输出行数
var autoHeight = function (elem) {
    // elem.style.height = 'auto';
    elem.scrollTop = 0; //防抖动
    elem.style.height = elem.scrollHeight + 'px';

    $(".solveConsole").find(".solveEditorSpot").css("height", (elem.scrollHeight + 26) + "px").empty();
    var len = elem.scrollHeight / 24;
    for (var i = 0; i < len; i++) {
        var li = '<div class="solveSpotList">' + (i + 1) + '</div>';
        $(".solveConsole").find(".solveEditorSpot").append(li);
    }
};
var textID = document.getElementById('consoleEditor');

// autoHeight(textID);

/**
 * 页面中相关事件在此函数中定义
 */
function registerEvent() {
    $(".shrinkBut").click(function () {
        if ($(this).hasClass("on")) {
            $(this).removeClass("on");
            $(".solveWrap").removeClass("on")
        } else {
            $(this).addClass("on");
            $(".solveWrap").addClass("on")
        }
        editorRefresh()
    });

    $(".editorTogBut").click(function () {
        if ($(this).parents(".solveEditorWrap").hasClass("on")) {
            $(this).parents(".solveEditorWrap").removeClass("on")
        } else {
            $(this).parents(".solveEditorWrap").addClass("on")
        }
        editorRefresh()

    });

    // 运行按钮响应事件
    $(".runBtn").click(function () {

        if ($("#customerInputCheck").is(":checked")) {
            $(".solveCheckTxtWrap").css("display", "block");
            return;
        }

        // var html = $(".codeEdit").html();
        // html = html.replace(/<div>/gi, "").replace(/<\/div>/gi, "").replace(/&lt;/gi, "<").replace(/&gt;/gi, ">").replace(/&nbsp;/gi, " ").replace(/&amp;/gi, "&");
        var code = codeEditor.getValue();
        var rematchId = $(this).attr("rematchId");
        $.post(SERVER_BASE_PATH + "/api/testCode/run",
            {
                source_code: btoa(code),
                is_customize: '0',
                customize_data: "",
                topic_id: rematchId,
                token: tokens
                // student_num: "test-001", // 待删除
                // topic_name: "first", // 待删除
            }, function (result) {
                resultToResult(result);
            });
    });

    $(document).on("click", ".submitBtn", function () {
        let needSubmit = window.confirm("是否需要提交？");

        if (needSubmit) {
            var code = codeEditor.getValue();
            var rematchId = $(".runBtn").attr("rematchId");
            $.post(SERVER_BASE_PATH + "/api/testCode/submit",
                {
                    source_code: btoa(code),
                    topic_id: rematchId,
                    token: tokens
                }, function (result) {
                    console.log(result);
                });
        }
    })

    $(document).on("click", ".clearBtn", function () {
        let selectResult = window.confirm("是否清空代码？");
        if (selectResult) {
            codeEditor.setValue("");
        }
    });

    $(document).on("click", ".undoBtn", function () {
        codeEditor.undo();
    });

    $("#submit").click(function () {
        $(".solveCheckTxtWrap").css("display", "none");

        var code = codeEditor.getValue();

        var customizeData = $(".customerInput").html();
        customizeData = customizeData.replace(/<div>/gi, "&nbsp;").replace(/<\/div>/gi, "&nbsp;")
            .replace(/&lt;/gi, "<").replace(/&gt;/gi, ">").replace(/&nbsp;/gi, " ").replace(/<br>/gi, "");

        if (customizeData == '') {
            return;
        }

        var rematchId = $(".runBtn").attr("rematchId");
        $.post(SERVER_BASE_PATH + "/api/testCode/run",
            {
                source_code: btoa(code),
                is_customize: '1',
                customize_data: btoa(customizeData),
                topic_id: rematchId,
                token: tokens
            }, function (result) {
                resultToResult(result);
            });
    });

    $("#cancel").click(function () {
        $(".solveCheckTxtWrap").css("display", "none");
    });

    $("#clear").click(function () {
        $(".customerInput").html("");
    });
}

/**
 * 调用接口获取对应题目
 * @param topicId
 */
function loadRematchTopic(topicId) {
    if (topicId == null || topicId == undefined || topicId == '') {
        console.warn("参数错误");
        return;
    }

    var param = {
        id: topicId
    };

    $.get(SERVER_BASE_PATH + "/api/testCode/getRematchById", param, function (data) {
        if (data["is_success"]) {
            var item = data["data"];
            $(".solveDescTxt").html(item["topic_content"]);
            $(".runBtn").attr("rematchId", item["id"]);
        }
    });
}

function judgeLogin() {

    if (!tokens) {
        layTxt('您还没登录!');
        setTimeout(function () {
            setUrl('overyears', 'login')//设置跳转
        }, 1000)
    }
}

$(function () {
    judgeLogin();
    registerEvent();
    loadRematchTopic(3);
});